package com.qianfeng.smartplatform.security.handlers;

//
//                            _ooOoo_  
//                           o8888888o  
//                           88" . "88  
//                           (| -_- |)  
//                            O\ = /O  
//                        ____/`---'\____  
//                      .   ' \\| |// `.  
//                       / \\||| : |||// \  
//                     / _||||| -:- |||||- \  
//                       | | \\\ - /// | |  
//                     | \_| ''\---/'' | |  
//                      \ .-\__ `-` ___/-. /  
//                   ___`. .' /--.--\ `. . __  
//                ."" '< `.___\_<|>_/___.' >'"".  
//               | | : `- \`.;`\ _ /`;.`/ - ` : | |  
//                 \ \ `-. \_ __\ /__ _/ .-` / /  
//         ======`-.____`-.___\_____/___.-`____.-'======  
//                            `=---='  
//  
//         .............................................  
//                  佛祖镇楼                  BUG辟易  
//          佛曰:  
//                  写字楼里写字间，写字间里程序员；  
//                  程序人员写程序，又拿程序换酒钱。  
//                  酒醒只在网上坐，酒醉还来网下眠；  
//                  酒醉酒醒日复日，网上网下年复年。  
//                  但愿老死电脑间，不愿鞠躬老板前；  
//                  奔驰宝马贵者趣，公交自行程序员。  
//                  别人笑我忒疯癫，我笑自己命太贱；  
//  


import com.fasterxml.jackson.databind.ObjectMapper;
import com.qianfeng.smartplatform.cache.RoleCache;
import com.qianfeng.smartplatform.dto.R;
import com.qianfeng.smartplatform.mapper.RoleMapper;
import com.qianfeng.smartplatform.pojo.BaseUser;
import com.qianfeng.smartplatform.pojo.Menu;
import com.qianfeng.smartplatform.pojo.Role;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.SimpleUrlAuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * Created by Jackiechan on 2022/1/7/11:49
 *
 * @author Jackiechan
 * @version 1.0
 * @since 1.0
 */
@Component
public class MyAuthenSuccessHandler extends SimpleUrlAuthenticationSuccessHandler {
    private ObjectMapper objectMapper;

    private RoleMapper roleMapper;

    private RoleCache roleCache;

    private ApplicationContext context;

    @Autowired
    public void setContext(ApplicationContext context) {
        this.context = context;
    }
    @Autowired
    public void setRoleCache(RoleCache roleCache) {
        this.roleCache = roleCache;
    }

    @Autowired
    public void setRoleMapper(RoleMapper roleMapper) {
        this.roleMapper = roleMapper;
    }

    @Autowired
    public void setObjectMapper(ObjectMapper objectMapper) {
        this.objectMapper = objectMapper;
    }
    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        //super.onAuthenticationSuccess(request, response, authentication);
        BaseUser principal = (BaseUser) authentication.getPrincipal();//获取当前登录的用户,类似于session中保存了用户的数据.这个结果就是我们的MyUserDetailService中方法的返回值
       // String username = principal.getUsername();//获取到登录的用户名
        Long userId = principal.getUserId();
       // Collection grantedAuthorities = authentication.getAuthorities();//获取用户现在已经有的权限
        List<SimpleGrantedAuthority> authorityList = new ArrayList<>();
        List<Long> roleIds = roleMapper.selectRoleIdByUserId(userId);//查询到了用户相关的所有的角色的id
        roleIds.stream().forEach(roleId->{//遍历用户所有的角色
            Role role = roleCache.getValue(roleId);//获取到当前角色id对应的角色
            List<Menu> menuList = role.getMenuList();//用户能访问的菜单集合
            //把每个菜单的权限获取出来设置给当前用户就可以
            //List<SimpleGrantedAuthority> authorityList = menuList.parallelStream().map(Menu::getPerms).map(SimpleGrantedAuthority::new).collect(Collectors.toList());
           // grantedAuthorities.addAll(authorityList);//将权限添加给用户
            authorityList.addAll(menuList.parallelStream().map(Menu::getPerms).map(SimpleGrantedAuthority::new).collect(Collectors.toList()));
        });
        //重新设置权限
        SecurityContextHolder.getContext().setAuthentication(new UsernamePasswordAuthenticationToken(principal,authentication.getCredentials(),authorityList));
        response.setContentType("application/json;charset=utf-8");
       // context.publishEvent(new UserLoginEvent());
        R r = R.setOK();
        response.getWriter().write(objectMapper.writeValueAsString(r));
    }
}
